package com.mate.cloud.inventory.consumer;

import com.mate.cloud.inventory.message.OrderMessage;
import com.mate.cloud.inventory.service.InventoryService;
import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;



/**
 * 订单消息消费者，负责处理订单消息并扣减库存
 */
@Component
@RocketMQMessageListener(
        topic = "order_topic",  // 监听的Topic，与生产者一致
        consumerGroup = "inventory_consumer_group" , // 消费者组，与配置文件一致
        messageModel = MessageModel.CLUSTERING, // 确保此处引用正确
        consumeMode = ConsumeMode.CONCURRENTLY
)
public class OrderMessageConsumer implements RocketMQListener<OrderMessage> {

    @Resource
    private InventoryService inventoryService;

    @Override
    public void onMessage(OrderMessage message) {
        System.out.println("接收到订单消息: " + message);

        // 处理消息：扣减库存
        boolean result = inventoryService.deductInventory(
                message.getProductId(),
                message.getQuantity()
        );

        if (result) {
            System.out.println("订单消息处理成功，订单ID: " + message.getOrderId());
        } else {
            System.out.println("订单消息处理失败，订单ID: " + message.getOrderId());
            // 实际项目中可以在这里实现重试逻辑或发送到死信队列
        }
    }

}
